package com.xxx.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.xxx.util.IpUtil;

/**
 * 系统过滤器
 * 
 * 
 * 
 */
public class SystemFilter implements Filter {
	
	// 允许跨域访问的IP白名单列表
	private static final List<String> allowIpList = Arrays.asList(
				"localhost",
				"127.0.0.1"
			);
	
	public FilterConfig config;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        // exclude处理
        String requestURI = request.getServletPath();
        boolean isNeedFilter = true;
        String excludeStr = config.getInitParameter("exclude");
        if(!StringUtils.isEmpty(excludeStr)) {
        	String [] excludeArr = excludeStr.split(";");
        	for(String exclude : excludeArr) {
        		if(requestURI.indexOf(exclude)>-1) { // requestURI包含exclude
        			isNeedFilter = false;
        			break;
        		}
        	}
        }
        
        if(isNeedFilter) {
        	String reqOrigin = request.getHeader("origin"); // 标识跨域资源请求
        	String domain = IpUtil.getDomain(reqOrigin); 	// origin里的域名或IP
        	
        	// 开放跨域（请求服务端设置Access-Control-Allow-Origin响应字段）
        	if(!StringUtils.isEmpty(domain) && allowIpList.contains(domain)) { // 允许跨域
        		response.setHeader("Access-Control-Allow-Origin", reqOrigin);
        		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        		response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, User-Agent, Token");
        	}
        }

        chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		config = null;
	}

}
